package com.example.thread.demo.alternate.print4;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 两个线程，一个打印1-100的奇数，一个打印1-100的偶数；要求：线程1打印5个之后，线程2开始打印，线程2打印5个之后，线程1再开始打印，以此循环。
 */
public class Solution {

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    private static int one = 1;

    private static int two = 2;

    private static boolean flag = false;

    public static void main(String[] args) {
        Solution solution = new Solution();
        Thread t1 = new Thread(solution.new NumberOne());
        Thread t2 = new Thread(solution.new NumberTwo());
        t1.start();
        t2.start();
    }

    class NumberOne implements Runnable {
        @Override
        public void run() {
            while (one < 100) {
                lock.lock();
                try {
                    if (flag) {
                        condition.await();
                    }
                    for (int i = 0; i < 5; i++) {
                        System.out.println("A: " + one);
                        one += 2;
                    }
                    flag = true;
                    condition.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    class NumberTwo implements Runnable {
        @Override
        public void run() {
            while (two < 101) {
                lock.lock();
                try {
                    if (!flag) {
                        condition.await();
                    }
                    for (int i = 0; i < 5; i++) {
                        System.out.println("B: " + two);
                        two += 2;
                    }
                    flag = false;
                    condition.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}
